package ink.tsg.zookeeper.controller;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author geo_tsg
 * @version 1.0.0
 * @ClassName TestController.java
 * @Description
 * @createTime 2021-11-18
 */
@RestController
public class TestController {

    @Autowired
    private ITbCommodityInfoService tbCommodityInfoService;

    @GetMapping
    public String h() {
        return tbCommodityInfoService.outsale() ? "success" : "fail";
    }

    @GetMapping("zookeeper")
    public String zookeeper() {
        //设置重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
        // 启动客户端
        client.start();
        InterProcessMutex mutex = new InterProcessMutex(client, "/locks");
        try {
            //加锁
            if (mutex.acquire(3, TimeUnit.SECONDS)) {
                return tbCommodityInfoService.zookeeper() ? "success" : "fail";
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            try {
                mutex.release();
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "error";
    }
}
